# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

# library(MetaboAnalystR)
library(ggrepel)
library(optparse)
library(tidyverse)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

option_list <- list(
make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
select(c("SampleID", "ClassNote"))

classNotes <- sampleInfo %>%
.$ClassNote %>%
unique()
cn <- combn(classNotes, 2)
for (i in 1 : ncol(cn)) {
    row <- cn[, i]
    group1Name <- row[1]
    group2Name <- row[2]
    parent <- paste0(group2Name, "_", group1Name)
    createWhenNoExist(parent)
    fileName <- paste0(parent, "/Diff_Table_", group2Name, "_", group1Name, ".csv")
    outFileName <- paste0(parent, "/Vplot_", group2Name, "_", group1Name, "_label.pdf")
    data <- read.csv(fileName, header = T, stringsAsFactors = F, comment.char = "")
    pBase <- 0.05

    logP5 <- log(0.05, pBase)
    logP1 <- log(0.1, pBase)
    plotData <- data %>%
        mutate(logFc = log(FC, 1.2)) %>%
        mutate(logP = log(Pvalue, pBase)) %>%
        rowwise() %>%
        do({
            result <- as.data.frame(.)
            logP <- result["logP"]
            col <- if (logP >= logP5) {
                "height"
            }else if (logP >= logP1) {
                "median"
            }else "low"
            result$col <- col
            result
        }) %>%
        mutate(col = factor(col, levels = c("height", "median", "low"))) %>%
        as.data.frame()

    print(head(plotData))

    minX <- min(plotData$logFc)
    maxX <- max(plotData$logFc)
    absMaxX <- max(abs(maxX), abs(minX))
    annoX <- - absMaxX
    annoX
    breaks <- seq(- floor(absMaxX), floor(absMaxX), 2)
    breaks

    labelData <- plotData %>%
        arrange(desc(logP)) %>%
        top_n(10, wt = logP)

    labelData

    p <- ggplot(plotData, mapping = aes(x = logFc, y = logP, colour = col)) +
        theme_bw(base_size = 8.8, base_family = "Times") +
        theme(axis.text.x = element_text(size = 9, vjust = 0.5),
        axis.text.y = element_text(size = 8.8), legend.position = 'none',
        axis.title.y = element_text(size = 11), legend.margin = margin(t = 0.3, b = 0.1, unit = 'cm'),
        legend.text = element_text(size = 6), axis.title.x = element_text(size = 11), panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), plot.title = element_text(hjust = 0.5, size = 13)
        ) +
        xlab("log1.2 Fold Change") +
        ylab("log0.05 P-Value") +
        ggtitle("Mann-Whitney U test") +
        geom_hline(aes(yintercept = logP5), colour = "#A9A9A9", linetype = 2, size = 0.375) +
        annotate("text", x = annoX , y = logP5 + 0.01, label = "P=0.05", color = "#006400", vjust = 0, hjust = 0 ,
        size = 2, family = "Times") +
        geom_hline(aes(yintercept = logP1), colour = "#A9A9A9", linetype = 2, size = 0.45) +
        annotate("text", x = annoX , y = logP1 + 0.01, label = "P=0.1", color = "#0000FF", vjust = 0, hjust = 0 ,
        size = 2, family = "Times") +
        geom_vline(aes(xintercept = 1), colour = "#A9A9A9", linetype = 2, size = 0.3) +
        geom_vline(aes(xintercept = - 1), colour = "#A9A9A9", linetype = 2, size = 0.3) +
        scale_x_continuous("log1.2 Fold Change", breaks = breaks, limits = c(- round(absMaxX), round(absMaxX))) +
        scale_colour_manual("", values = c("#006400", "#0000FF", "#BEBEBE")) +
    #point
        geom_point(aes(), size = 2, stroke = 0) +
        geom_text_repel(segment.size=0.2,data = labelData, aes(x = logFc, y = logP, label = Name), size = 2, family = "Times", color = "black")

    ggsave(limitsize = FALSE,outFileName, p, width = 7, height = 5)
}





